package system

import (
	"errors"
	"goweb/web/global"
	"goweb/web/model/system"
	userReq "goweb/web/model/system/request"
	"goweb/web/utils"

	"gorm.io/gorm"
)

type UserService struct{}

// 实现 UserService 的增删改查接口(Java mapper层)
func (b *UserService) Create(uc userReq.UserCreateRequest) (system.User, error) {
	// 判断该username是否存在
	var u system.User
	if !errors.Is((global.DB.Where("username = ?", uc.Username).First(&u).Error), gorm.ErrRecordNotFound) {
		return u, errors.New("账号已经被注册")
	}

	var user system.User
	user.Avatar = uc.Avatar
	user.NickName = uc.NickName
	user.Username = uc.Username
	user.Password = utils.GetByteMd5([]byte(uc.Password))
	user.Uuid = utils.UUID()
	user.Status = 1

	// 插入数据库
	return user, global.DB.Create(&user).Error
}

func (b *UserService) Update(user system.User) (system.User, error) {
	// 更新数据库
	return user, global.DB.Updates(&user).Error
}

// 分页
func (b *UserService) Page(userPage userReq.UserPageRequest) (interface{}, int64, error) {
	page := userPage.PageInfo
	username := userPage.Username

	limit := page.PageSize
	offset := (page.PageNum - 1) * page.PageSize
	db := global.DB.Model(&system.User{})

	if username != "" {
		db.Where("username = ?", username)
	}

	if status := userPage.Status; status != 0 {
		db.Where("status = ?", status)
	}

	var userList []system.User
	var total int64
	// 统计total
	var err error
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&userList).Error
	return userList, total, err
}

// 列表
func (b *UserService) List() (interface{}, error) {
	db := global.DB.Model(&system.User{})
	var userList []system.User
	err := db.Where("status = ?", 1).Find(&userList).Error
	return userList, err
}

// 详情
func (b *UserService) GetById(uuid string) (error, system.User) {
	var u system.User
	return global.DB.Model(&u).Where("uuid = ?", uuid).Find(&u).Error, u
}

// 根据uuid删除
func (b *UserService) DeleteById(uuid string) error {
	return global.DB.Delete(&system.User{}, "uuid = ?", uuid).Error
}

// 根据uuid批量删除
func (b *UserService) DeleteBatchByUuid(uuids []string) error {
	return global.DB.Delete(&system.User{}, "uuid in ?", uuids).Error
}

func (b *UserService) Login(u *system.User) (*system.User, error) {
	var user system.User
	err := global.DB.Where("username = ?", u.Username).First(&user).Error
	pwd := utils.GetByteMd5([]byte(u.Password))
	if err != nil || user.Password != pwd {
		return u, errors.New("用户密码错误")
	}
	return &user, err
}
